package geektime.spring.springbucks.customerservice.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import geektime.spring.springbucks.customerservice.integration.CoffeeOrderService;
import geektime.spring.springbucks.customerservice.integration.CoffeeService;
import geektime.spring.springbucks.customerservice.model.Coffee;
import geektime.spring.springbucks.customerservice.model.CoffeeOrder;
import geektime.spring.springbucks.customerservice.model.NewOrderRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerController {

  @Autowired
  private CoffeeService coffeeService;
  @Autowired
  private CoffeeOrderService coffeeOrderService;

  @GetMapping("/menu")
  public List<Coffee> readMenu() {
    List<Coffee> list = coffeeService.getAll();
    log.info("readMenu");
    return list == null ? Collections.emptyList() : list;
  }

  @PostMapping("/order")
  @HystrixCommand(fallbackMethod = "fallbackCreateOrder")
  public CoffeeOrder createOrder() {
    NewOrderRequest orderRequest = NewOrderRequest.builder()
        .customer("Li Lei")
        .items(Arrays.asList("capuccino"))
        .build();
    log.info("createOrder");
    CoffeeOrder order = coffeeOrderService.create(orderRequest);
    log.info("Order ID :{}", order == null ? "-" : order.getId());
    return order;
  }

  public CoffeeOrder fallbackCreateOrder(){
    log.warn("Fallback to Null order.");
    return null;
  }
}
